#coding:utf8
'''
Created on 2013-9-22

@author: jt
'''
from firefly.utils.singleton import Singleton
from app.db import playerdb
from twisted.python import log




class PlayerManager(object):
    '''玩家管理类'''
    __metaclass__ = Singleton
    
    def __init__(self):
        self.players={}  #key:pid, value:player类
        
    def getPlayer(self,pid):
        '''根据角色id获取角色实例
        @param pid: int 角色id
        '''
        return self.players.get(pid,None)
    
    def addPlayer(self,player):
        '''添加玩家
        @param player: Player 类
        '''
        self.players[player.id]=player
        
    def addPlayerByPid(self,pid):
        '''根据玩家id添加'''
        from app.scense.core.user.player import Player
        player=Player(pid)
        self.players[pid]=player
        
    def addPlayerByUname(self,uname):
        '''根据玩家登陆账号添加'''
        info=playerdb.getByuname(uname)
        if not info:
            log.err("uname:%s  is not (playerdb.getByuname(uname))"%uname)
        pid=info.get('id')#玩家id
        self.addPlayerByPid(pid)
    
    def dropBypid(self,pid):
        '''根据玩家id删除角色实例'''
        if not self.players.has_key(pid):
            return False
        player=self.players[pid]
        player.closes()#角色下线前保存数据处理
        del self.players[pid]
        return True
    
    def dropPlayer(self,player):
        '''删除玩家实例'''
        pid=player.id
        self.dropBypid(pid)
        
    def updatePlayerDid(self,did,pid):
        '''更改角色的登陆动态id'''
        player=self.players.get(pid,None)
        if not player:
            return False
        player.setDid(did)
        return True
        
    
        
        
        
        